﻿using System;
using System.Messaging;

namespace ShuttleBus.Transports.Msmq
{
    public class MsmqQueue : IQueue
    {
        private readonly int _secondsToProcessMessage;
        private readonly BinaryMessageFormatter _formatter;
        private readonly MessageQueue _queue;

        public MsmqQueue(IEndpoint endpoint, int secondsToProcessMessage, MessageQueue queue)
        {
            _secondsToProcessMessage = secondsToProcessMessage;
            _queue = queue;
            Endpoint = endpoint;
            _formatter = new BinaryMessageFormatter();
        }

        public void Dispose()
        {
            _queue.Dispose();
        }

        public IEndpoint Endpoint { get; set; }

        public void Send(object message, Uri location)
        {
            if (message == null || location == null)
            {
                return;
            }
            var queuePath = location.ToMsmqPath();

            CreateQueueIfNotExists(queuePath);

            using (var queue = new MessageQueue(queuePath))
            {
                queue.Formatter = _formatter;
                var msmqMessage = new System.Messaging.Message
                    {
                        Body = message,
                        Formatter = _formatter
                    };
                queue.Send(msmqMessage);
            }
        }

        public bool HasMessage(out BaseMessage message)
        {
            var msmqMessage = _queue.Receive(TimeSpan.FromSeconds(_secondsToProcessMessage));
            if (msmqMessage != null)
            {
                message = new MsmqMessage(msmqMessage);
                return true;
            }

            message = null;
            return false;
        }

        public void RemoveMessage(BaseMessage message)
        {
            // no op for msmq
        }

        private static void CreateQueueIfNotExists(string path)
        {
            if (!MessageQueue.Exists(path))
            {
                MessageQueue.Create(path);
            }
        }

    }
}